package com.qiyeji.real_estate.controller;

import com.qiyeji.real_estate.entity.*;
import com.qiyeji.real_estate.service.ProjectService;
import com.qiyeji.real_estate.service.StaffService;
import com.qiyeji.real_estate.service.WorkService;
import com.qiyeji.real_estate.utils.Result;
import org.camunda.bpm.engine.FormService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.form.TaskFormData;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Comment;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/Task")
@RestController
public class TaskController {

    @Autowired
    TaskService taskService;

    @Autowired
    ProjectService projectService;

    @Autowired
    WorkService workService;

    @Autowired
    HistoryService historyService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    FormService formService;

    @Autowired
    StaffService staffService;

    //通过负责人名称获取任务列表
    @PostMapping("GetTaskBySCode")
    public Result getTask(@RequestBody Map<String, String> params) {
        String sCode = params.get("sCode");
        List<Task> tasks = null;
        try {
            tasks = taskService.createTaskQuery().taskAssignee(sCode).active().list();
        } catch (Exception e) {
            return Result.noTasks();
        }
        List<TaskData> taskDatas = new ArrayList<>();
        if (tasks == null) {
            return Result.noTasks();
        }
        else {
            for (Task task: tasks) {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
                project project = projectService.queryProjectByPCode(processInstance.getBusinessKey());
                TaskFormData formData = formService.getTaskFormData(task.getId());;
                String type = formData.getFormKey();
                System.out.println("type: " + type);
                if (type.equals("Feedback")) {
                    TemporaryWorkKey temporaryWorkKey = workService.select(project.getPcode());
                    HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(temporaryWorkKey.getTaskID()).singleResult();
                    staff s = staffService.queryStaff(historicTaskInstance.getAssignee());
                    List<Comment> comments = taskService.getTaskComments(temporaryWorkKey.getTaskID());
                    taskDatas.add(new TaskData(s.getSname(), task.getName(), task.getId(), task.getExecutionId(), project.getPname(), comments.get(0).getFullMessage(),type));
                }
                else if (type.equals("AcceptTask")) {
                    TemporaryWorkKey temp = workService.selectForParentTaskID(sCode, processInstance.getBusinessKey());
                    HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(temp.getTaskID()).singleResult();
                    staff s = staffService.queryStaff(historicTaskInstance.getAssignee());
                    List<String> members = workService.getMembersByPCode(project.getPcode());
                    List<String> members1 = workService.getMembersBypCode(project.getPcode());
//                    System.out.println(members.toString());
//                    System.out.println(members1.toString());
                    if (members1.size() == 0){
                        taskDatas.add(new TaskData(s.getSname(), task.getName(), task.getId(), task.getExecutionId(), project.getPname(), type, members));
                    } else {
                        if (members.addAll(members1)) {
                            taskDatas.add(new TaskData(s.getSname(), task.getName(), task.getId(), task.getExecutionId(), project.getPname(), type, members));
                        }else
                            System.out.println("拼接失败！");
                    }
                }else
                    taskDatas.add(new TaskData(task.getName(), task.getId(), task.getExecutionId(), project.getPname(),type));
            }
            System.out.println(taskDatas.toString());
            return Result.success(taskDatas);
        }
    }

    //通过任务信息完成分配任务
    @PostMapping("/CompleteTaskForDistribution")
    public Result completeTask(@RequestBody Map<String, Object> params) {
        TaskData taskData = new TaskData(
                params.get("taskName").toString(),
                params.get("taskID").toString(),
                params.get("taskExecutionId").toString(),
                params.get("projectName").toString(),
                params.get("type").toString());
        List<String> Workers = (ArrayList)params.get("workers");
        Task task = taskService.createTaskQuery().taskId(taskData.getTaskID()).active().singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        String pCode = processInstance.getBusinessKey();
        for (String worker: Workers) {
            System.out.println(worker);
            workService.insert(new TemporaryWorkKey(worker, pCode, taskData.getTaskID(), task.getId()));
        }
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    //通过任务信息完成接受任务
    @PostMapping("/CompleteTaskForAccept")
    public Result completeTaskForAccept(@RequestBody Map<String, Object> params) {
        TaskData taskData = new TaskData(
                params.get("taskName").toString(),
                params.get("taskID").toString(),
                params.get("taskExecutionId").toString(),
                params.get("projectName").toString(),
                params.get("type").toString());
        Task task = taskService.createTaskQuery().taskId(taskData.getTaskID()).active().singleResult();
        Boolean accept = (Boolean)params.get("accept");
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        String pCode = processInstance.getBusinessKey();
        if (!accept){
            workService.update(new TemporaryWorkKey(task.getAssignee(), pCode, taskData.getTaskID()));
            taskService.createComment(taskData.getTaskID(), null, params.get("comment").toString());
        }
        else
            workService.updateAll(new TemporaryWorkKey(task.getAssignee(), pCode, taskData.getTaskID()));

        runtimeService.setVariable(taskData.getTaskExecutionId(), "accept", accept);
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    //通过任务信息完成反馈任务
    @PostMapping("/CompleteTaskForFeedback")
    public Result completeTaskForFeedback(@RequestBody Map<String, String> params) {
        TaskData taskData = new TaskData(params.get("taskName"), params.get("taskID"), params.get("taskExecutionId"), params.get("projectName"), params.get("type"));
        Task task = taskService.createTaskQuery().taskId(taskData.getTaskID()).active().singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        workService.deleteByPCode(processInstance.getBusinessKey());
        String comment = "同意";
        taskService.createComment(taskData.getTaskID(), null, comment);
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    //通过任务信息完成模型审批任务
    @PostMapping("/CompleteTaskForModelApproval")
    public Result completeTaskForModelApproval(@RequestBody Map<String, Object> params) {
        TaskData taskData = new TaskData(
                params.get("taskName").toString(),
                params.get("taskID").toString(),
                params.get("taskExecutionId").toString(),
                params.get("projectName").toString(),
                params.get("type").toString());
        Boolean accept = (Boolean)params.get("accept");
        Task task = taskService.createTaskQuery().taskId(taskData.getTaskID()).active().singleResult();
        runtimeService.setVariable(taskData.getTaskExecutionId(), "accept", accept);
        String comment;
        if (accept) {
            comment = "通过";
        }
        else{
            comment = "驳回修改";
        }
        taskService.createComment(taskData.getTaskID(), null, comment);
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    //通过任务信息完成渲染或后期审批任务
    @PostMapping("/CompleteTaskForApproval")
    public Result completeTaskForApproval(@RequestBody Map<String, Object> params) {
        TaskData taskData = new TaskData(
                params.get("taskName").toString(),
                params.get("taskID").toString(),
                params.get("taskExecutionId").toString(),
                params.get("projectName").toString(),
                params.get("type").toString());
        Boolean accept = (Boolean)params.get("accept");
        Integer option = (Integer)params.get("option");
        System.out.println(option);
        Task task = taskService.createTaskQuery().taskId(taskData.getTaskID()).active().singleResult();
        runtimeService.setVariable(taskData.getTaskExecutionId(), "accept", accept);
        String comment;
        if (accept)
            comment = "通过";
        else {
            comment = "驳回修改";
            runtimeService.setVariable(task.getExecutionId(), "option", option);
        }
        taskService.createComment(taskData.getTaskID(), null, comment);
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    // 员工上传成品并完成任务
    @PostMapping("/CompleteTaskForWorker")
    public Result completeTaskForWorkder(@RequestBody Map<String, Object> params){
        TaskData taskData = new TaskData(
                params.get("taskName").toString(),
                params.get("taskID").toString(),
                params.get("taskExecutionId").toString(),
                params.get("projectName").toString(),
                params.get("type").toString());
        taskService.complete(taskData.getTaskID());

        return Result.success();
    }

    // 通过员工ID获取历史任务列表
    @PostMapping("/GetHistoricTasks")
    public Result getHistoricTasks(@RequestBody Map<String, String> params) {
        String sCode = params.get("sCode");
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().taskAssignee(sCode).finished().list();
        if (historicTaskInstances.isEmpty()) {
            return Result.noHistoricTask();
        }else {
            List<HistoricTask> historicTasks = new ArrayList<>();
            for (HistoricTaskInstance historicTaskInstance: historicTaskInstances) {
                historicTasks.add(new HistoricTask(
                        historicTaskInstance.getId(),
                        historicTaskInstance.getName(),
                        staffService.queryStaff(historicTaskInstance.getAssignee()).getSname(),
                        historicTaskInstance.getStartTime().toString(),
                        historicTaskInstance.getEndTime().toString()
                ));
            }
            return Result.success(historicTasks);
        }
    }

}
